<template>
  <div class="user-login-container">
    <div class="pc_login">
      <!-- 右侧登录注册容器 -->
      <div class="login-end-container">
        <!-- 组件容器 -->
        <div class="login_end_module">
          <!-- 介绍语句 -->
          <div class="introduce">
            <div class="title">
              <p class="text">登录</p>
              <p class="solid"></p>
            </div>
            <div class="toRegister">
              没有账号？<a
                href="javascript:;"
                @click="$router.replace('/user/register')"
                >点此注册</a
              >
            </div>
            <!-- <div class="subtitle">按步骤填写信息完成注册流程</div> -->
          </div>
          <!-- 输入框区域 -->
          <div class="input_area">
            <div v-show="!toggle.login_method">
              <el-form ref="loginForm" :rules="rules" :model="ruleForm">
                <el-form-item label="" prop="nickname">
                  <span class="" ref="nickname">邮箱/用户名</span>
                  <el-input v-model="ruleForm.nickname"></el-input>
                </el-form-item>
                <el-form-item label="" prop="password">
                  <span class="" ref="password">密码</span>
                  <el-input
                    v-model="ruleForm.password"
                    type="password"
                    style="padding-right: 20px"
                    v-show="!toggle.showWord"
                  ></el-input>
                  <el-input
                    v-show="toggle.showWord"
                    v-model="ruleForm.password"
                    type="input"
                    style="padding-right: 20px"
                  ></el-input>
                  <div class="operation" style="text-align: right">
                    <a href="javascript:;">
                      <i
                        @click="toggleModule"
                        class="iconfont"
                        :class="
                          toggle.showWord ? 'icon-yanjing' : 'icon-yanjing1'
                        "
                      ></i>
                    </a>
                  </div>
                </el-form-item>
              </el-form>
            </div>
            <div v-show="toggle.login_method">
              <el-form ref="emailLoginForm" :rules="rules" :model="ruleForm">
                <el-form-item label="" prop="email" ref="emailElem">
                  <span class="" ref="email">邮箱</span>
                  <el-input
                    v-model="ruleForm.email"
                    type="email"
                    style="padding-right: 20px"
                  ></el-input>
                  <div class="operation" style="width: 100px">
                    <a
                      href="javascript:;"
                      @click="sendEmailCode"
                      :style="
                        toggle.sendCode
                          ? 'color: #999; cursor: not-allowed !important;'
                          : ''
                      "
                      >{{ toggle.sendCode ? toggle.time : "发送验证码" }}</a
                    >
                  </div>
                </el-form-item>
                <el-form-item label="" prop="code">
                  <span class="" ref="code">验证码</span>
                  <el-input v-model="ruleForm.code"></el-input>
                </el-form-item>
              </el-form>
            </div>
            <div class="remember">
              <el-checkbox v-model="ruleForm.userTcp">
                <span class="tcp"> 记住我 </span>
              </el-checkbox>
              <div @click="toggleLoginMethod">
                <a href="javascript:;">{{
                  toggle.login_method ? "用户名密码登录" : "短信验证登录"
                }}</a>
              </div>
            </div>
          </div>
          <!-- 确定提交 -->
          <div class="submit">
            <el-button type="primary" :loading="loading" @click="register()"
              >开始登录</el-button
            >
          </div>
          <!-- 忘记密码 -->
          <div class="forget_password">
            <a href="javascript:;">已有账号，忘记密码？</a>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { throttle } from "lodash";
import {
  name_validator,
  password_validator,
  email_validator,
  userTcp_validator,
  code_validator,
} from "@/utils/validate";

export default {
  name: "UserLogin",
  data() {
    return {
      // 切换合集
      toggle: {
        // 切换密码显示
        showWord: false,
        // 发送验证码
        sendCode: false,
        // 用于倒计时的验证码
        time: 59,
        // 倒计时的定时器
        timer: null,
        // 切换账号密码和验证码登录   false账号密码 | true邮箱验证
        login_method: false,
      },
      // 校验图片路径和描述信息
      ruleForm: {
        // 昵称
        nickname: "",
        // 密码
        password: "",
        // 邮箱
        email: "",
        // 验证码
        code: "",
        // 是否勾选协议
        userTcp: true,
      },
      rules: {
        // 用户名
        nickname: [
          {
            validator: name_validator,
            trigger: "blur",
            required: true,
          },
        ],
        // 密码
        password: [
          {
            validator: password_validator,
            trigger: "blur",
            required: true,
          },
        ],
        // 邮箱
        email: [
          {
            validator: email_validator,
            trigger: "blur",
            required: true,
          },
        ],
        // 验证码
        code: [
          {
            validator: code_validator,
            trigger: "blur",
            required: true,
          },
        ],
        // 用户协议
        userTcp: [
          {
            validator: userTcp_validator,
            trigger: "blur",
            required: true,
          },
        ],
      },
      loading: false,
    };
  },
  methods: {
    // 切换密码明文显示
    toggleModule() {
      this.toggle.showWord = !this.toggle.showWord;
    },
    // 发送验证码，节流处理
    sendEmailCode: throttle(function () {
      // 发送了验证码后不能继续发送
      if (this.toggle.sendCode) return;
      // 发送验证码
      this.$api.sendCode(this.ruleForm.email).then((res) => {
        if (res.code === 200) {
          this.toggle.sendCode = true;
          // 开启定时器
          this.toggle.timer = setInterval(() => {
            this.toggle.time--;
            if (this.toggle.time <= 0) {
              clearInterval(this.toggle.timer);
              this.toggle.sendCode = false;
              this.toggle.time = 59;
            }
          }, 1000);
        }
      });
    }, 2000),
    // 开始登录验证
    register: throttle(function () {
      const formName = this.toggle.login_method
        ? "emailLoginForm"
        : "loginForm";
      // 已发布状态代码
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (this.loading) return;
          this.sendLoginRequest();
        } else {
          return false;
        }
      });
    }, 2000),
    // 根据不同登录方式，发送不同登录请求
    sendLoginRequest() {
      // 登录状态
      this.loading = true;
      const jwt = this.toggle.login_method;
      // 判断登录方式     false邮箱用户名密码 | true邮箱验证
      if (jwt) {
        // 邮箱验证登录
        const { email, code } = this.ruleForm;
        // 邮箱用户名密码
        const options = {
          email: email.trim(),
          code: code.trim(),
          loginType: "email",
        };
        // 发送请求
        this.$store
          .dispatch("user/Login", options)
          .then((res) => {
            if (res?.code === 200) {
              this.loading = false;
              this.$win("登录成功");
              this.$router.replace("/community/article");
            }
          })
          .catch(() => {
            this.loading = false;
          });
      } else {
        // 邮箱用户名密码登录
        const { nickname, password } = this.ruleForm;
        const options = {
          password: password.trim(),
        };
        if (nickname.trim().indexOf("@") === -1) {
          options["userName"] = nickname.trim();
        } else {
          options["email"] = nickname.trim();
        }
        options.loginType = "account";
        // 发送请求
        this.$store
          .dispatch("user/Login", options)
          .then((res) => {
            if (res?.code === 200) {
              this.loading = false;
              this.$win("登录成功");
              this.$router.replace("/community/article");
            }
          })
          .catch(() => {
            this.loading = false;
          });
      }
    },
    // 切换登录方式
    toggleLoginMethod() {
      // 清空验证文本内容
      if (this.toggle.login_method) {
        this.ruleForm.email = "";
        this.ruleForm.code = "";
        this.$refs["nickname"].classList.remove("letter_active");
        this.$refs["password"].classList.remove("letter_active");
        // 清空表单错误信息
        this.$refs.emailLoginForm.resetFields();
      } else {
        this.ruleForm.nickname = "";
        this.ruleForm.password = "";
        this.$refs["email"].classList.remove("letter_active");
        this.$refs["code"].classList.remove("letter_active");
        // 清空表单错误信息
        this.$refs.loginForm.resetFields();
      }
      this.toggle.login_method = !this.toggle.login_method;
    },
    // 初始化事件
    _initEvent() {
      // 实现渐入渐出
      document
        .querySelectorAll(".user-login-container .el-form-item__content")
        .forEach((item) => {
          // 给每一个绑定获得焦点事件
          const elem = item.querySelectorAll(".el-input__inner");
          /**
           * 循环两次解决切换明文密码切换时，让input节点发生了改变，导致focus和blur事件失效问题
           */
          elem.forEach((item2) => {
            if (item2 === null) return;
            const span = item.querySelector("span");
            item2.onfocus = function () {
              span.classList.add("letter_active");
            };
            item2.onblur = function () {
              if (this.value.trim() !== "") return;
              span.classList.remove("letter_active");
            };
          });
        });
    },
  },
  mounted() {
    this._initEvent();
  },
};
</script>

<style lang="less" scoped>
.user-login-container {
  .pc_login {
    height: calc(100vh - 64px);
    display: flex;
    background: #f0f2f5;
    background-image: url("@/assets/images/login/bg.svg");
    background-repeat: no-repeat;
    background-position: center 110px;
    background-size: 100%;
    /* 水平垂直居中 */
    display: flex;
    align-items: center;
    justify-content: center;
    /deep/.el-form-item__error {
      padding-top: 8px;
    }
    // 右侧登录注册容器
    .login-end-container {
      margin-top: -80px;
      .login_end_module {
        width: 500px;
        background: #fff;
        border-radius: 12px;
        box-shadow: 0 4px 12px rgb(0 0 0 / 8%), 0 0 1px rgb(1 0 0 / 10%);
        padding: 50px;
        .introduce {
          text-align: left;
          margin-bottom: 50px;
          display: flex;
          justify-content: space-between;
          .title {
            flex: auto;
            position: relative;
            height: 45px;
            margin-bottom: 8px;
            & > p {
              margin-bottom: 0;
            }
            .text {
              font-size: 30px;
              position: absolute;
              font-weight: 700;
              z-index: 2;
            }
            .solid {
              max-width: 60px;
              position: absolute;
              left: 0;
              bottom: 4px;
              background: #f2f2f2;
              height: 12px;
              width: 100%;
            }
          }
          .subtitle {
            color: #999;
            font-size: 14px;
          }
          .toRegister {
            line-height: 53px;
            a {
              color: #359eff;
              &:hover {
                color: #359eff !important;
              }
            }
          }
        }
        .submit {
          margin-top: 20px;
          width: 100%;
          button {
            width: 100% !important;
          }
        }
        .forget_password {
          margin-top: 36px;
          a {
            color: #359eff;
            &:hover {
              color: #359eff !important;
            }
          }
        }
      }
    }
    // 调整输入框
    /deep/ .el-form-item:nth-of-type(2) .el-form-item__content {
      margin-bottom: -6px !important;
    }
    .remember {
      border-bottom: 0 !important;
      margin-bottom: 0;
      display: flex;
      margin-top: 24px !important;
      justify-content: space-between;
      a {
        color: #359eff;
        &:hover {
          color: #359eff !important;
        }
      }
    }
    /deep/ .el-form-item__content {
      display: flex;
      position: relative;
      margin-bottom: 20px;
      border-radius: 0;
      border-bottom: 3px solid #e1e1e1 !important;
      & > span {
        position: absolute;
        z-index: 0;
        /* 水平垂直居中 */
        position: absolute;
        top: 50%;
        left: 0;
        transform: translateY(-50%);
        font-size: 18px;
        transition: font 0.3s, top 0.3s, transform 0.3s;
        color: #999;
      }
      .el-input {
        height: 42px;
        input {
          font-size: 16px;
          background: #ffffff00;
          padding: 0 !important;
          height: 100%;
          border: 0;
        }
      }
      .el-checkbox {
        cursor: url("@/assets/mouse/x1.cur"), auto !important;
        .el-checkbox__input {
          cursor: url("@/assets/mouse/x2.cur"), auto !important;
        }
        .el-checkbox__label {
          .tcp {
            color: #999;
            a {
              transition: color 0.4s;
              &:hover {
                color: var(--a-button-hover-color);
              }
            }
          }
        }
      }
      .operation {
        padding-right: 10px;
        text-align: right;
        // 出现浮入效果
        a {
          transition: color 0.4s;
          &:hover {
            color: var(--a-button-hover-color);
          }
        }
      }
    }
    // 输入框汉字上调样式类名
    .letter_active {
      font-size: 14px !important;
      top: -30px !important;
      transform: translateY(0) !important;
    }
  }
}
</style>